package pl.edu.agh.mobilne;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

public class Scheduler {
	
	public static final String PREFS_NAME = "medicalScheduleFile";
	private List<List<String>> schedule = null;
	public static Set<String> taskToDo = new TreeSet<String>();
	
	public void setSchedule(Context context){
		
		try {
			
			for(List<String> scenario: schedule){
				String scenarioString = "";
				Boolean scenarioBegining = true;
				
				Integer hour = null;
				Integer minute = null;

				
				for(String subtask : scenario){
					if(subtask.matches("[0-9]{1,2}:[0-9]{2}")){
						
						String [] time = subtask.split(":");
						
						if(scenarioBegining){
							hour = new Integer(time[0]);
						 	minute = new Integer(time[1]);
						}
						else{
							setAlarm(context, scenarioString, hour, minute);
							scenarioString = "";
							hour += new Integer(time[0]);
							minute += new Integer(time[1]);
							
							if(minute > 59){
								hour += minute/60;
								minute = minute%60;
							}
						}
						
						scenarioBegining = false;
					}
					else{
						
						if(subtask.equals("Send")){
							setAlarm(context, scenarioString, hour, minute);
							scenarioString = "";
						}
						else
							scenarioString += subtask + ";";
					}
					
					
				}
			}
			


		} catch (Exception e) {
		   	Log.e("Scheduler", "ERROR IN CODE:"+e.toString());
		}
		
	}
	

	private void setAlarm(Context context, String scenarioString, Integer hour, Integer minute) {
		Log.d("Scheduler", "\n---Set alarm-: " + hour + ":" + minute);
		Calendar cal_now = Calendar.getInstance();
		Calendar cal = Calendar.getInstance();
		
		cal.set(Calendar.HOUR_OF_DAY, hour);
		cal.set(Calendar.MINUTE, minute);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		
		if(cal.after(cal_now)){
			Log.d("Scheduler", "\n---alarm ok");
			Intent intent = new Intent(context, Reminder.class);
			intent.putExtra("scenario", scenarioString);
			PendingIntent sender = PendingIntent.getBroadcast(context, new Random().nextInt(), intent, PendingIntent.FLAG_ONE_SHOT);
	
			AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
			am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
		}
	}


	public void update(Context context){
		
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpUriRequest request = new HttpGet("http://10.0.2.2:8080/blog/schedules/current");
		
		String scheduleJson = null;
		
		try {
			HttpResponse response = httpclient.execute(request);
			Reader reader = null;
	        try {
	            reader = new InputStreamReader(response.getEntity().getContent());

	            StringBuffer sb = new StringBuffer();
	            {
	                int read;
	                char[] cbuf = new char[1024];
	                while ((read = reader.read(cbuf)) != -1)
	                    sb.append(cbuf, 0, read);
	            }
	            scheduleJson = sb.toString();
	            parse(context, scheduleJson);
	            
				SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
		        SharedPreferences.Editor editor = settings.edit();
		        editor.putString("schedule", scheduleJson);
		        editor.commit();

	        } finally {
	            if (reader != null) {
	                try {
	                    reader.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public void parse(Context context, String scheduleJson){
		schedule = new LinkedList<List<String>>();
		
		try {
			JSONObject jsonMainObject = new JSONObject(scheduleJson);
			for(int j=0; j<jsonMainObject.length(); j++){
				List<String> scenario = new LinkedList<String>();
				
				JSONArray jsonArray = jsonMainObject.getJSONArray(Integer.toString(j));
				for(int i=0; i < jsonArray.length(); i++){
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					String name = jsonObject.getString("name");
					if(name.equals("Time"))
						scenario.add(jsonObject.getString("value"));
					else if(name.equals("Delay"))
						scenario.add(jsonObject.getString("value"));
					else	
						scenario.add(name);
				}
				
				schedule.add(scenario);
			}
			
			setSchedule(context);
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}
